package com.qdlc.p2p.biz.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.UserVipUpRateService;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.LogTplNid;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.dao.BorrowCollectionDao;
import com.qdlc.p2p.dal.dao.BorrowDao;
import com.qdlc.p2p.dal.dao.UserDao;
import com.qdlc.p2p.dal.dao.UserVipUprateCollectionDao;
import com.qdlc.p2p.dal.dto.Borrow;
import com.qdlc.p2p.dal.dto.BorrowCollection;
import com.qdlc.p2p.dal.dto.BorrowTender;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserVipUprateCollection;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.model.interest.EachPlan;
import com.qdlc.p2p.dal.model.interest.InterestCalculator;
import com.qdlc.p2p.dal.util.SystemConfigs;
/**
 * vip加息业务处理
 * @author zlhx
 * @version 2.0
 * @date 2015-06-17 14:25
 */
@Service("userVipUpRateService")
public class UserVipUpRateServiceImpl implements UserVipUpRateService {
	
	private static Logger logger = Logger.getLogger(UserVipUpRateServiceImpl.class); 

	@Resource
	private BorrowCollectionDao borrowCollectionDao;
	
	@Resource
	private UserVipUprateCollectionDao userVipUprateCollectionDao;
	
	@Resource
	private BorrowDao borrowDao;
	
	@Resource
	private UserDao userDao;

	@Resource
	private AccountService accountService;

	@Override
	public void borrowSuccessVipUpRate(BorrowTender borrowTender, String accountLogType, double extraRate) {
		if(borrowTender == null || borrowTender.getBorrow() == null){
			logger.debug("发放vip加息失败！原因为投标信息异常！");
			return;
		}
		Borrow borrow = borrowTender.getBorrow();
		long userId = borrowTender.getUser().getUserId();
		double tenderAccount = borrowTender.getAccount();
		double newApr = BigDecimalUtil.div(BigDecimalUtil.add(borrow.getApr(), extraRate),100);
		//获取计算器类型
		InterestCalculator ic = BorrowModel.doInterestCalculator(borrow.getStyle(), tenderAccount, newApr, borrow.getBorrowTimeType(), borrow.getTimeLimit());
		List<EachPlan> eachPlanList = ic.getEachPlanList();//获取新利息的每一期还款详情
		
		//根据新投标利率，计算出新的每一期待收利息记录，将每一期利息差值保存到数据库中
		double newAprTotalInterest = BigDecimalUtil.sub(ic.repayTotal(), tenderAccount); //新投标利率所获得利息总和
		double newInterest = BigDecimalUtil.sub(newAprTotalInterest, borrowTender.getInterest());
		double totalInterest = 0; //新利息总额
		List<UserVipUprateCollection> vipUpRateCollectList = new ArrayList<UserVipUprateCollection>();
		List<BorrowCollection> cList = borrowCollectionDao.getCollectionByTender(borrowTender.getId());
		for(int i = 0; i < cList.size(); i++){
			BorrowCollection borrowCollection = cList.get(i);
			EachPlan each = eachPlanList.get(i);
			UserVipUprateCollection vipUpRateCollect = new UserVipUprateCollection();
			vipUpRateCollect.setBorrowId(borrow.getId());
			vipUpRateCollect.setUserId(userId);
			vipUpRateCollect.setStatus(0);
			vipUpRateCollect.setCollectionId(borrowCollection.getId()); //待收id
			vipUpRateCollect.setOldInterest(borrowCollection.getInterest());  //原始利率利息
			vipUpRateCollect.setNewInterest(each.getInterest());  //设置产生的新利息
			vipUpRateCollect.setPeriod(borrowCollection.getPeriod());  //设置期数
			vipUpRateCollect.setRepayYesInterest(0);
			vipUpRateCollect.setUserId(borrowCollection.getUser().getUserId());
			vipUpRateCollect.setRepaymentTime(borrowCollection.getRepaymentTime());
			vipUpRateCollect.setRepayInterest(BigDecimalUtil.sub(each.getInterest(), borrowCollection.getInterest()));  //设置利息差值
			if (i== eachPlanList.size() - 1) {  //最后一期做差值
				double different = BigDecimalUtil.sub(newAprTotalInterest, totalInterest);
				vipUpRateCollect.setNewInterest(different);
				vipUpRateCollect.setRepayInterest(BigDecimalUtil.sub(different, borrowCollection.getInterest()));  //设置利息差值
			}
			totalInterest = BigDecimalUtil.add(totalInterest, each.getInterest());
			vipUpRateCollectList.add(vipUpRateCollect);
		}
		//保存vip加息代收记录
		userVipUprateCollectionDao.save(vipUpRateCollectList);

		//更新账户代收
		Global.setTransfer(LogTplNid.LOG_TPL_KEY, accountLogType);
		Global.setTransfer("web_url", SystemConfigHelper.getValue(SystemConfigHelper.Nid.WEB_URL));
		Global.setTransfer("borrow", borrow);
		Global.setTransfer("newInterest", newInterest);
		accountService.addCollectionAndTotal(borrowTender.getUser().getUserId(), SystemConfigs.ADMIN_ID, newInterest);
	}

	@Override
	public void borrowRepaySuccessVipUpRate(long collectionId, String accountLogType) {
		UserVipUprateCollection vipUprateColl = userVipUprateCollectionDao.getUserVipUprateCollByCollId(collectionId);
		
		if (null == vipUprateColl ) {
			logger.info("此待收没有相应的vip加息记录：id--->"+collectionId);
			return;
		}
		
		logger.info("开始处理vip待收加息-collectionId-->"+collectionId+",期数："+vipUprateColl.getPeriod());
		Borrow borrow = borrowDao.find(vipUprateColl.getBorrowId());
		//处理加息部分每一期的待收额外收益,加息部分收益由平台垫付
		User user = userDao.find(vipUprateColl.getUserId());  //获取加息投资用户
		//平台垫付加息收益
		double repayInterest = vipUprateColl.getRepayInterest();
		//更新用户资金
		Global.setTransfer(LogTplNid.LOG_TPL_KEY, LogTplNid.BORROW_SUCCESS);
		Global.setTransfer("web_url", SystemConfigHelper.getValue(SystemConfigHelper.Nid.WEB_URL));
		Global.setTransfer("borrow", borrow);
		Global.setTransfer("money", repayInterest);
		accountService.revokeCapital(user.getUserId(), SystemConfigs.ADMIN_ID, repayInterest);

		//更新加息券额外收益还款状态
		vipUprateColl.setStatus(1);
		vipUprateColl.setRepaymentYesTime(DateUtil.getNow());
		vipUprateColl.setRepayYesInterest(repayInterest);
		userVipUprateCollectionDao.update(vipUprateColl);
		logger.info("vip待收加息处理完成-collectionId-->"+collectionId+",期数："+vipUprateColl.getPeriod());
	}

	@Override
	public List<Object[]> getVipUpRateCollectionInterest(User user, String date) {
		return userVipUprateCollectionDao.getVipUpRateCollectionInterest(user, date);
	}
}
